package net.misp.beta.nomilog.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class StoreHelper extends SQLiteOpenHelper {

	Context mContext;
	static final String DB_NAME = "store_database";
	static final int DB_VERSION = 1;

	private InputStream mInputStream;
	private InputStreamReader mInputStreamReader;
	private AssetManager mAssets;

	public StoreHelper(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
		mContext=context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createDatabase(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	private void createDatabase(final SQLiteDatabase db) {
		char[] buffer = new char[1024];
		int i = 0;
		try {
			mAssets = mContext.getAssets();
			mInputStream = mAssets.open("nomilog.sqlite");
			mInputStreamReader = new InputStreamReader(mInputStream, "utf-8");
			String sql = "";
			while (-1 != (mInputStreamReader.read(buffer))) {
				label: while (i < 1024) {
					for (; buffer[i] != ';';) {
						if (buffer[i] == '\n' || buffer[i] == '\r'
								|| buffer[i] == '\t') {
							i++;
							continue;
						}
						sql += buffer[i];
						i++;
						if (i >= 1024) {
							break label;
						}
					}
					sql += buffer[i];
					db.execSQL(sql);
					sql = "";
					i++;
				}
				i = 0;
				buffer = new char[1024];
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ArrayIndexOutOfBoundsException e) {
			Log.v("arrayIndexOuntObBounds", "buffer[" + i + "]=" + buffer[i]);
		}
	}

}
